import { Dropdown, MenuProps } from "@/components/base";
import ICapability from "../interfaces/ICapability";
import React from "react";
import { filterCapability } from "../funs/filterCapability";
import { v4 as uuidV4 } from 'uuid';

type Items = { key: string, capability: ICapability<any> }[];

export interface ICapabilityDropdownProps<IData = any> {
    capabilities: ICapability[];
    data?: IData;
    index?: number;
    children?: React.ReactNode;
}

export function CapabilityDropdown<IData = any>(props: ICapabilityDropdownProps<IData>) {

    const [capabilityList, setCapabilityList] = React.useState<Items>([]);
    const onClick = React.useRef<any>();

    const subMenu = React.useMemo(() => {
        if (props.capabilities) {
            return filterCapability(props.capabilities, props.data || {}, props.index);
        } else {
            return [];
        }
    }, [props])

    const items = React.useMemo(() => {
        const l: { key: string, capability: ICapability<any> }[] = [];
        const s = c(subMenu);
        setCapabilityList(l.filter(e => !!e.capability?.useExpand));

        function c(subMenu: ICapability<any>[] | undefined): MenuProps['items'] {
            if (subMenu) {
                return subMenu.map((s: ICapability<any>, i: number) => {
                    const key = `${s.id}-${i}-${uuidV4()}`
                    const children = c(s.subMenu);
                    l.push({ key, capability: s });
                    return {
                        key,
                        label: s.title,
                        disabled: s.isDisabled?.(props.data || {}, props.index || 0),
                        children: children?.length ?? 0 > 0 ? children : undefined,
                        onClick: () => { onClick?.current?.(key) }
                    }
                })
            } else {
                return [];
            }
        }

        return s;
    }, [props.data, props.index, subMenu]);

    return (
        <>
            {capabilityList && capabilityList.length > 0 && <Element s={capabilityList} init={e => { onClick.current = e; }} />}
            {capabilityList && capabilityList.length > 0 && <Dropdown menu={{ items }} trigger={['click']}>
                {props.children}
            </Dropdown>}
        </>
    )
}

function Element(props: { s: Items, init: (onClick: (key: string) => void) => void }) {

    const { s } = props;
    const item = s.map(e => ({ key: e.key, expand: e.capability.useExpand?.({}, 0) }));

    const onClick = React.useCallback((key: string) => {
        const e = item.find(e => e.key === key);
        if (e) {
            e.expand?.onClick?.();
        }
    }, [item]);

    React.useEffect(() => {
        props.init(onClick);
    }, [onClick, props])

    return (
        item.map(e => e?.expand?.element)
    )
}